package com.systemsjr.mpf.expense;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;

import com.systemsjr.mpf.IntentHandler;
import com.systemsjr.mpf.R;
import com.systemsjr.mpf.account.AccountInstance;
import com.systemsjr.mpf.account.AccountInstanceList;

public class ManageExpenseActivity extends Activity {

	private Cursor c;
	private final HashMap<String, AccountInstance> instancesMap = new HashMap<String, AccountInstance>();
	private final HashMap<String, ExpenseType> typesMap = new HashMap<String, ExpenseType>();

	public static final String[] PROJECTIONS = { Expense.ID,
			Expense.DESCRIPTION, Expense.EXPENSE_TYPE,
			Expense.ACCOUNT_INSTANCE, Expense.AMOUNT };

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_manage_expense);
		final Expense expense = new Expense();

		final SimpleDateFormat sdf = new SimpleDateFormat(Expense.DATE_FORMAT);

		final AutoCompleteTextView typeText = (AutoCompleteTextView) findViewById(R.id.type_of_expense);
		final AutoCompleteTextView instanceText = (AutoCompleteTextView) findViewById(R.id.expense_instance_account);
		final EditText description = (EditText) findViewById(R.id.description);
		final EditText expenseDate = (EditText) findViewById(R.id.expenseDate);
		final EditText amount = (EditText) findViewById(R.id.amount);

		expenseDate.setText(sdf.format(new Date()));

		/*****************************************************************************************************
		 * Setup ExpenseType view
		 *****************************************************************************************************/
		Cursor typeCursor = getContentResolver().query(ExpenseType.CONTENT_URI,
				ExpenseType.PROJECTIONS, null, null, null);
		String[] types = new String[typeCursor.getCount()];
		int i = 0;
		while (typeCursor.moveToNext()) {
			ExpenseType t = new ExpenseType();
			t.setId(typeCursor.getLong(typeCursor
					.getColumnIndex(ExpenseType.ID)));
			t.setCode(typeCursor.getString(typeCursor
					.getColumnIndex(ExpenseType.CODE)));
			t.setExpenseType(typeCursor.getString(typeCursor
					.getColumnIndex(ExpenseType.EXPENSE_TYPE)));
			typesMap.put(t.getExpenseType(), t);
			types[i] = t.getExpenseType();
			i++;
		}

		typeCursor.close();
		ArrayAdapter<String> typeAdapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_list_item_1, types);
		typeText.setAdapter(typeAdapter);

		/*****************************************************************************************************
		 * Setup AccountInstance view
		 *****************************************************************************************************/

		Cursor instanceCursor = getContentResolver().query(
				AccountInstance.CONTENT_URI, AccountInstance.PROJECTIONS,
				AccountInstance.ACTIVE_INSTANCES, null, null);
		String[] instances = new String[instanceCursor.getCount()];
		// System.out.println("found instances " + instances.length);
		i = 0;
		while (instanceCursor.moveToNext()) {
			AccountInstance ai = new AccountInstance();
			ai.setBudget(instanceCursor.getDouble(instanceCursor
					.getColumnIndex(AccountInstance.BUDGET)));
			ai.setInstance(instanceCursor.getString(instanceCursor
					.getColumnIndex(AccountInstance.INSTANCE)));
			ai.setId(instanceCursor.getLong(instanceCursor
					.getColumnIndex(AccountInstance.ID)));
			ai.setBudget(instanceCursor.getDouble(instanceCursor
					.getColumnIndex(AccountInstance.BUDGET)));
			instances[i] = ai.getInstance();
			instancesMap.put(ai.getInstance(), ai);

			// System.out.println("instance is " + ai.getInstance());
			i++;
		}

		instanceCursor.close();
		ArrayAdapter<String> instanceAdapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_list_item_1, instances);
		instanceText.setAdapter(instanceAdapter);

		/**
		 * Process input from the list activity
		 */
		Bundle bundle = getIntent().getExtras();

		if (bundle != null && bundle.size() > 0) {

			if (bundle.get(Expense.TABLE_NAME) != null) {
				Expense exp = (Expense) bundle.get(Expense.TABLE_NAME);
				expense.setId(exp.getId());
				expense.setAccountInstance(exp.getAccountInstance());
				expense.setAmount(exp.getAmount());
				expense.setDescription(exp.getDescription());
				expense.setExpenseDate(exp.getExpenseDate());
				expense.setExpenseType(exp.getExpenseType());
			}
		}

		amount.setText("" + expense.getAmount());
		description.setText(expense.getDescription() == null ? "" : expense
				.getDescription());
		expenseDate
				.setText(sdf.format(expense.getExpenseDate() == null ? new Date()
						: expense.getExpenseDate()));
		instanceText.setText(expense.getAccountInstance() == null ? ""
				: expense.getAccountInstance().getInstance());
		typeText.setText(expense.getExpenseType() == null ? "" : expense
				.getExpenseType().getExpenseType());

		Button saveButton = (Button) findViewById(R.id.saveExpenseButton);
		saveButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				expense.setAmount(Double.parseDouble(amount.getText()
						.toString()));

				expense.setDescription(description.getText().toString());
				expense.setAccountInstance(instancesMap.get(instanceText
						.getText().toString()));
				expense.setExpenseType(typesMap.get(typeText.getText()
						.toString()));

				try {
					if (expenseDate.getText().toString().length() == 10) {
						expense.setExpenseDate(sdf.parse(expenseDate.getText()
								.toString()));
					} else {
						expense.setExpenseDate(null);
					}

				} catch (ParseException e) {
					e.printStackTrace();
				}

				ContentResolver cr = getContentResolver();
				ContentValues values = new ContentValues();

				values.put(Expense.AMOUNT, expense.getAmount());
				values.put(Expense.DESCRIPTION, expense.getDescription());

				if (expense.getExpenseDate() != null) {

					values.put(Expense.EXPENSE_DATE,
							sdf.format(expense.getExpenseDate()));
				}

				values.put(Expense.EXPENSE_TYPE, expense.getExpenseType()
						.getId());
				values.put(Expense.ACCOUNT_INSTANCE, expense
						.getAccountInstance().getId());

				if (expense.getAccountInstance() != null
						&& expense.getDescription() != null
						&& expense.getDescription().length() > 0) {
					if (expense.getId() == null || expense.getId() == 0) {
						cr.insert(Expense.CONTENT_URI, values);

						String s = Expense.DESCRIPTION + " = '"
								+ expense.getDescription() + "' AND "
								+ Expense.ACCOUNT_INSTANCE + " = "
								+ expense.getAccountInstance().getId()
								+ " AND " + Expense.EXPENSE_TYPE + " = "
								+ expense.getExpenseType().getId();
						Cursor c = cr.query(Expense.CONTENT_URI,
								Expense.PROJECTIONS, s, null, null);
						if (c.moveToFirst()) {
							expense.setId(c.getLong(c
									.getColumnIndex(Expense.ID)));
						}
						c.close();
					} else {
						cr.update(Expense.CONTENT_URI, values, "_id = "
								+ expense.getId(), null);
					}
				}

				showList(expense);
			}
		});

		Button newButton = (Button) findViewById(R.id.newExpenseButton);
		newButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				expense.setExpenseDate(null);
				expense.setExpenseType(null);
				expense.setAccountInstance(null);
				expense.setAmount(0.00);
				expense.setDescription(null);

				amount.setText("0.00");
				description.setText(null);
				typeText.setText(null);
				expenseDate.setText(null);
				instanceText.setText(null);

				typeText.setEnabled(true);
				instanceText.setEnabled(true);
				description.setEnabled(true);
				instanceText.setEnabled(true);
				amount.setEnabled(true);
			}
		});

		Button deleteButton = (Button) findViewById(R.id.deleteExpenseButton);
		deleteButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				ContentResolver cr = getContentResolver();
				if (expense.getId() != null || expense.getId() > 0) {
					cr.delete(Expense.CONTENT_URI, "_id = " + expense.getId(),
							null);
				}

				amount.setText("0.00");
				description.setText(null);
				typeText.setText(null);
				expenseDate.setText(null);
				instanceText.setText(null);

				expense.setId(0L);
				try {
					expense.setExpenseDate(sdf.parse(expenseDate.getText()
							.toString()));
				} catch (ParseException e) {
					e.printStackTrace();
				}

				expense.setAccountInstance(instancesMap.get(instanceText
						.getText().toString()));
				expense.setExpenseType(typesMap.get(typeText.getText()
						.toString()));
				expense.setDescription(description.getText().toString());
				expense.setAmount(Double.parseDouble(amount.getText()
						.toString()));

				showList(expense.clone());
			}
		});

		Button searchButton = (Button) findViewById(R.id.searchExpenseButton);
		searchButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				expense.setAmount(Double.parseDouble(amount.getText()
						.toString()));

				expense.setDescription(description.getText().toString());
				expense.setAccountInstance(instancesMap.get(instanceText
						.getText().toString()));
				expense.setExpenseType(typesMap.get(typeText.getText()
						.toString()));

				try {
					if (expenseDate.getText().toString().length() == 10) {
						expense.setExpenseDate(sdf.parse(expenseDate.getText()
								.toString()));
					} else {
						expense.setExpenseDate(null);
					}

				} catch (ParseException e) {
					e.printStackTrace();
				}

				Expense e = expense.clone();

				expense.setExpenseDate(null);
				expense.setExpenseType(null);
				expense.setAccountInstance(null);
				expense.setAmount(0);
				expense.setDescription(null);

				amount.setText("0.00");
				description.setText(null);
				typeText.setText(null);
				expenseDate.setText(null);
				instanceText.setText(null);

				showList(e);
			}
		});

		if (instancesMap.size() == 0 || typesMap.size() == 0) {
			// TODO: show a dialog
			typeText.setEnabled(false);
			instanceText.setEnabled(false);
			description.setEnabled(false);
			instanceText.setEnabled(false);
			amount.setEnabled(false);

		} else {
			typeText.setEnabled(true);
			instanceText.setEnabled(true);
			description.setEnabled(true);
			instanceText.setEnabled(true);
			amount.setEnabled(true);
		}
	}

	private void showList(Expense exp) {
		Intent intent = new Intent(this, ExpenseList.class);
		if (exp != null) {
			intent.putExtra(Expense.TABLE_NAME, exp);
		}

		startActivityForResult(intent, 1);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.manage_expense, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		Intent intent = IntentHandler.handleOnOptionsItemSelected(this,
				item.getItemId());
		startActivityForResult(intent, 1);
		return super.onOptionsItemSelected(item);
	}
}
